import { PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import { Upload, message } from "antd";
import { Component, useState } from "react";
import Cloud from "leancloud-storage";
const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG/PNG file!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isJpgOrPng && isLt2M;
};

class ImgUpload extends Component {
  state = {
    loading: false,
    imageUrl: "",
  };
  handleChange = (info) => {
    console.log(info);
    getBase64(info.file, async (base64) => {
      console.log(base64);
      let res = await new Cloud.File("react-admin-2301.png", { base64 }).save();
      console.log(res);
      let { url } = res.attributes;
      this.props.onChange(url); //向表单元素提交图片链接
      this.setState({
        imageUrl: url,
      });
    });
  };
  uploadButton = (
    <div>
      {this.loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  render() {
    console.log("图片组件的props", this.props);
    let { imageUrl } = this.state;
    return (
      <>
        <Upload
          name="avatar"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          beforeUpload={beforeUpload}
          customRequest={this.handleChange}
        >
          {imageUrl ? (
            <img
              src={imageUrl}
              alt="avatar"
              style={{
                width: "100%",
              }}
            />
          ) : (
            this.uploadButton
          )}
        </Upload>
      </>
    );
  }
}
export default ImgUpload;
